package org.batatasframework.support.database.values;

import java.sql.ResultSet;

import org.batatasframework.support.database.spi.ResultWritable;
import org.batatasframework.support.database.sql.field.SelectFragment;
import org.batatasframework.support.format.BooleanFormat;


public class BooleanValueHolder extends AbstractSingleValueHolder{

	private final BooleanFormat format;
	
	public BooleanValueHolder(SelectFragment field, String alias, Object format) {
		super(field, alias);
		if(format instanceof BooleanFormat){
			this.format = (BooleanFormat)format;
		}else{
			this.format = BooleanFormat.DEFAULT;
		}
	}
	
	@Override
	public FieldValue read(ResultSet rs) throws Exception {
		return new BooleanValue(rs.getBoolean(alias));
	}

	@Override
	public StatisticsTotal createStatistics() {
		return new BooleanStatistics();
	}
	
	class BooleanStatistics implements StatisticsTotal{

		private int sumTrueValue;
		private int sumFalseValue;
		
		private class BooleanStatisticsValue implements StatisticsValue{
			
			private int trueValue;
			private int falseValue;
			
			@Override
			public void read(ResultSet rs) throws Exception {
				if(rs.getBoolean(alias)){
					trueValue++;
					sumTrueValue++;
				}else{
					falseValue++;
					sumFalseValue++;
				}
			}

			@Override
			public void writeTo(ResultWritable resultWriter) throws Exception {
				resultWriter.append(trueValue);
				resultWriter.append(falseValue);
			}
			
		}
		
		@Override
		public StatisticsValue newValue() {
			return new BooleanStatisticsValue();
		}
		
		@Override
		public void writeTo(ResultWritable resultWriter) throws Exception {
			resultWriter.append(sumTrueValue);
			resultWriter.append(sumFalseValue);
		}
		
		@Override
		public String[] getItemNames() {
			return new String[]{ format.getTrueValue(), format.getFalseValue() };
		}
	}

	class BooleanValue extends AbstractValue<Boolean>{
		
		public BooleanValue(Boolean value) {
			super(value);
		}
		
		@Override
		public Object targetValue() {
			return format.format(value);
		}
	}
}
